#include "server.h"
#include <QDebug>
#include <QWebSocket>
#include <QFile>
#include <QFileInfo>
#include <QUuid>
#include <QPixmap>
#include <QIcon>




/***********************************************
* 一些工具函数
************************************************/
static inline QString GetFileName(const QString filePath)
{
    QFileInfo fileinfo(filePath);
    return fileinfo.fileName();
}

//日志的宏函数
#define TAG QString("[%1:%2]").arg(GetFileName(__FILE__),QString::number(__LINE__))
#define LOG() qDebug().noquote() << TAG

//产生唯一ID
static inline QString makeId()
{
    return  "M" + QUuid::createUuid().toString().sliced(25,12);    //仅取部分
}

//格式化好的时间
static inline QString formatTime(int64_t timestamp)
{
    QDateTime datetime = QDateTime::fromSecsSinceEpoch(timestamp);
    return datetime.toString("yyyy-MM-dd HH:mm:ss");
}

//获取时间戳
static inline int64_t getTime()
{
    return QDateTime::currentSecsSinceEpoch();
}

//文件读写
static inline QByteArray loadFile2ByteArray(QString filePath)
{
    QFile file(filePath);
    // LOG() << "文件路径：" << filePath;
    if(!file.open(QFile::ReadOnly))
    {
        LOG() << "读文件打开失败,原因：" << file.errorString();
        return QByteArray();
    }
    QByteArray content = file.readAll();
    file.close();//别忘记关闭文件
    return content;
}

static inline void writeByteArray2File(QString filePath,const QByteArray content)
{
    QFile file(filePath);
    if(!file.open(QFile::WriteOnly))
    {
        LOG() << "写文件打开失败";
        return;
    }
    file.write(content);
    file.flush();
    file.close();
}


//QByteArray 转 QIcon
static inline QIcon QByteArray2QIcon(const QByteArray& byteArray)
{
    QPixmap pixmap;
    pixmap.loadFromData(byteArray);
    QIcon icon(pixmap);
    return icon;
}


HttpServer* HttpServer::instance = nullptr;

HttpServer *HttpServer::getInstance()
{
    if(instance == nullptr)
    {
        instance = new HttpServer();
    }
    return instance;
}

pbPackage::UserInfo makeUserInfo(int index, const QByteArray &avatar)
{
    pbPackage::UserInfo userInfo;
    userInfo.setUserId(QString::number(1000 + index));
    userInfo.setDescription("好好吃饭");
    userInfo.setNickname("张三" + QString::number(index));
    userInfo.setPhone("123456789" + QString::number(index));
    userInfo.setAvatar(avatar);
    return userInfo;
}

pbPackage::MessageInfo makeTextMessageInfo(int index, const QString& chatSessionId,const QByteArray &avatar)
{
    pbPackage::MessageInfo messageInfo;
    messageInfo.setMessageId(QString::number(3000 + index));
    messageInfo.setChatSessionId(chatSessionId);
    messageInfo.setSender(makeUserInfo(index,avatar));
    messageInfo.setTimestamp(getTime());

    pbPackage::StringMessageInfo stringMessageInfo;
    stringMessageInfo.setContent("这是一条会话信息" + QString::number(index));

    pbPackage::MessageContent messageContent;
    messageContent.setMessageType(pbPackage::MessageTypeGadget::STRING);
    messageContent.setStringMessage(stringMessageInfo);

    messageInfo.setMessage(messageContent);
    return messageInfo;
}



pbPackage::MessageInfo makeImageMessageInfo(int index, const QString& chatSessionId,const QByteArray &avatar)
{
    pbPackage::MessageInfo messageInfo;
    messageInfo.setMessageId(QString::number(3000 + index));
    messageInfo.setChatSessionId(chatSessionId);
    messageInfo.setSender(makeUserInfo(index,avatar));
    messageInfo.setTimestamp(getTime());

    pbPackage::ImageMessageInfo imageMessageInfo;
    //真实服务器推送的数据力，本身也就不包含图片，需要对方二次请求再获取
    imageMessageInfo.setFileId("testImage");

    pbPackage::MessageContent messageContent;
    messageContent.setMessageType(pbPackage::MessageTypeGadget::IMAGE);
    messageContent.setImageMessage(imageMessageInfo);
    messageInfo.setMessage(messageContent);
    return messageInfo;
}



pbPackage::MessageInfo makeFileMessageInfo(int index, const QString& chatSessionId,const QByteArray &avatar)
{
    pbPackage::MessageInfo messageInfo;
    messageInfo.setMessageId(QString::number(3000 + index));
    messageInfo.setChatSessionId(chatSessionId);
    messageInfo.setSender(makeUserInfo(index,avatar));
    messageInfo.setTimestamp(getTime());

    pbPackage::FileMessageInfo fileMessageInfo;
    //真实服务器推送的数据力，本身也就不包含文件内容，需要对方二次请求再获取
    fileMessageInfo.setFileId("testFile");
    fileMessageInfo.setFileName("你好.txt");
    fileMessageInfo.setFileSize(0);

    pbPackage::MessageContent messageContent;
    messageContent.setMessageType(pbPackage::MessageTypeGadget::FILE);
    messageContent.setFileMessage(fileMessageInfo);
    messageInfo.setMessage(messageContent);
    return messageInfo;
}



pbPackage::MessageInfo makeSpeechMessageInfo(int index, const QString& chatSessionId,const QByteArray &avatar)
{
    pbPackage::MessageInfo messageInfo;
    messageInfo.setMessageId(QString::number(3000 + index));
    messageInfo.setChatSessionId(chatSessionId);
    messageInfo.setSender(makeUserInfo(index,avatar));
    messageInfo.setTimestamp(getTime());

    pbPackage::SpeechMessageInfo speechMessageInfo;
    //真实服务器推送的数据力，本身也就不包含文件内容，需要对方二次请求再获取
    speechMessageInfo.setFileId("testSpeech");

    pbPackage::MessageContent messageContent;
    messageContent.setMessageType(pbPackage::MessageTypeGadget::SPEECH);
    messageContent.setSpeechMessage(speechMessageInfo);
    messageInfo.setMessage(messageContent);
    return messageInfo;
}

bool HttpServer::init()
{
    //进行端口号绑定、配置路由

    //1.绑定端口，成功则返回绑定的端口号
    int ret = httpServer.listen(QHostAddress::Any,8000);

    //2.配置路由
    httpServer.route("/ping",[](const QHttpServerRequest& req){
        (void)req;
        qDebug() << "[http] 收到 ping 请求";
        return "pong";
    });

    httpServer.route("/service/user/get_user_info",[=](const QHttpServerRequest& req){
        return this->getUserInfo(req);
    });

    httpServer.route("/service/friend/get_friend_list",[=](const QHttpServerRequest& req){
        return this->getFriendList(req);
    });

    httpServer.route("/service/friend/get_chat_session_list",[=](const QHttpServerRequest& req){
        return this->getChatSessionList(req);
    });

    httpServer.route("/service/friend/get_pending_friend_events",[=](const QHttpServerRequest& req){
        return this->getApplyList(req);
    });

    httpServer.route("/service/message_storage/get_recent",[=](const QHttpServerRequest& req){
        return this->getRecentMessage(req);
    });


    httpServer.route("/service/message_transmit/new_message",[=](const QHttpServerRequest& req){
        return this->newMessage(req);
    });

    httpServer.route("/service/user/set_nickname",[=](const QHttpServerRequest& req){
        return this->setNickName(req);
    });

    httpServer.route("/service/user/set_description",[=](const QHttpServerRequest& req){
        return this->setDesc(req);
    });

    httpServer.route("/service/user/get_phone_verify_code",[=](const QHttpServerRequest& req){
        return this->getPhoneVerifyCode(req);
    });


    httpServer.route("/service/user/set_phone",[=](const QHttpServerRequest& req){
        LOG() << "httpServer.route(/service/user/set_phone)";
        return this->setPhone(req);
    });

    httpServer.route("/service/user/set_avatar",[=](const QHttpServerRequest& req){
        return this->setAvatar(req);
    });

    httpServer.route("/service/friend/remove_friend",[=](const QHttpServerRequest& req){
        return this->removeFriend(req);
    });

    httpServer.route("/service/friend/add_friend_apply",[=](const QHttpServerRequest& req){
        return this->applyFriend(req);
    });

    httpServer.route("/service/friend/add_friend_process",[=](const QHttpServerRequest& req){
        return this->addFriendProcess(req);
    });


    httpServer.route("/service/friend/create_chat_session",[=](const QHttpServerRequest& req){
        return this->createChatSession(req);
    });

    httpServer.route("/service/friend/get_chat_session_member",[=](const QHttpServerRequest& req){
        return this->getMemberList(req);
    });

    httpServer.route("/service/friend/search_friend",[=](const QHttpServerRequest& req){
        return this->searchFriend(req);
    });

    httpServer.route("/service/message_storage/search_history",[=](const QHttpServerRequest& req){
        return this->searchHistoryByKey(req);
    });

    httpServer.route("/service/message_storage/get_history",[=](const QHttpServerRequest& req){
        return this->searchHistoryByTime(req);
    });

    httpServer.route("/service/user/username_login",[=](const QHttpServerRequest& req){
        return this->userLogin(req);
    });

    httpServer.route("/service/user/username_register",[=](const QHttpServerRequest& req){
        return this->userRegister(req);
    });

    httpServer.route("/service/user/phone_login",[=](const QHttpServerRequest& req){
        return this->phoneLogin(req);
    });

    httpServer.route("/service/user/phone_register",[=](const QHttpServerRequest& req){
        return this->phoneRegister(req);
    });

    httpServer.route("/service/file/get_single_file",[=](const QHttpServerRequest& req){
        return this->getSingleFile(req);
    });

    httpServer.route("/service/speech/recognition",[=](const QHttpServerRequest& req){
        return this->speechRecognition(req);
    });
    return ret == 8000;
}

QHttpServerResponse HttpServer::getUserInfo(const QHttpServerRequest &req)
{
    //1. 解析请求，将请求中的body取出来，进行反序列化
    pbPackage::GetUserInfoReq pbReq;
    pbReq.deserialize(&this->serialize,req.body());
    LOG() << "[pbReq 获得用户信息] requestId = " << pbReq.requestId() << ", loginSessionId = " << pbReq.sessionId();

    //2. 构造响应数据
    pbPackage::UserInfo userInfo;
    userInfo.setUserId("1029");
    userInfo.setDescription("这是个性签名");
    userInfo.setNickname("张三");
    userInfo.setPhone("13345612345");
    userInfo.setAvatar(loadFile2ByteArray("D:\\A_Bit_Code\\micro-service\\ChatMockServer\\resource\\LOGO.png"));
    pbPackage::GetUserInfoRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");
    pbResp.setUserInfo(userInfo);

    QByteArray body = pbResp.serialize(&serialize);


    //3. 构造http响应数据
    QHttpServerResponse httpResp(body,QHttpServerResponse::StatusCode::Ok);
    httpResp.setHeader("Content-Type", "application/x-protobuf");
    // LOG() << "服务器返回响应" << httpResp.statusCode();
    return httpResp;
}

QHttpServerResponse HttpServer::getFriendList(const QHttpServerRequest &req)
{
    //1.解析请求
    pbPackage::GetFriendListReq pbReq;
    pbReq.deserialize(&this->serialize,req.body());
    LOG() << "[pbReq 获得好友列表] requestId = " << pbReq.requestId() << ", loginSessionId = " << pbReq.sessionId();

    //2.构造响应
    pbPackage::GetFriendListRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");

    QByteArray avatar = loadFile2ByteArray("D:\\A_Bit_Code\\micro-service\\ChatMockServer\\resource\\panda.png");
    for(int i = 0; i < 20; ++i)
    {
        pbPackage::UserInfo userInfo = makeUserInfo(i,avatar);
        pbResp.friendList().push_back(userInfo);
    }
    //3.构造http响应
    QByteArray body = pbResp.serialize(&serialize);
    QHttpServerResponse httpResp(body,QHttpServerResponse::StatusCode::Ok);
    httpResp.setHeader("Content-Type", "application/x-protobuf");
    return httpResp;
}

QHttpServerResponse HttpServer::getChatSessionList(const QHttpServerRequest &req)
{
    //1.解析请求
    pbPackage::GetChatSessionListReq pbReq;
    pbReq.deserialize(&this->serialize,req.body());
    LOG() << "[pbReq 获得会话列表] requestId = " << pbReq.requestId() << ", loginSessionId = " << pbReq.sessionId();

    //2.构造响应
    pbPackage::GetChatSessionListRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");

    QByteArray avatar = loadFile2ByteArray("D:\\A_Bit_Code\\micro-service\\ChatMockServer\\resource\\lion.png");
    //创建若当单聊
    for(int i = 0; i < 10; ++i)
    {
        pbPackage::ChatSessionInfo chatSessionInfo;
        chatSessionInfo.setChatSessionId(QString::number(2000 + i));
        chatSessionInfo.setChatSessionName("会话" + QString::number(i));
        chatSessionInfo.setAvatar(avatar);
        chatSessionInfo.setSingleChatFriendId(QString::number(1000 + i));

        pbPackage::MessageInfo messageInfo = makeTextMessageInfo(i,chatSessionInfo.chatSessionId(),avatar);
        chatSessionInfo.setPrevMessage(messageInfo);
        pbResp.chatSessionInfoList().push_back(chatSessionInfo);
    }
    //创建群聊
    pbPackage::ChatSessionInfo chatSessionInfo;
    chatSessionInfo.setChatSessionId(QString::number(9999));
    chatSessionInfo.setChatSessionName("会话9999");
    chatSessionInfo.setAvatar(avatar);
    chatSessionInfo.setSingleChatFriendId("");

    pbPackage::MessageInfo messageInfo = makeTextMessageInfo(99,chatSessionInfo.chatSessionId(),avatar);
    chatSessionInfo.setPrevMessage(messageInfo);
    pbResp.chatSessionInfoList().push_back(chatSessionInfo);


    //3.构建http响应
    QByteArray body = pbResp.serialize(&serialize);
    QHttpServerResponse httpResp(body,QHttpServerResponse::StatusCode::Ok);
    httpResp.setHeader("Content-Type", "application/x-protobuf");
    return httpResp;
}

QHttpServerResponse HttpServer::getApplyList(const QHttpServerRequest &req)
{
    //1.解析请求
    pbPackage::GetPendingFriendEventListReq pbReq;
    pbReq.deserialize(&this->serialize,req.body());
    LOG() << "[pbReq 获的好友申请列表] requestId = " << pbReq.requestId() << ", loginSessionId = " << pbReq.sessionId();

    //2.构造响应
    pbPackage::GetPendingFriendEventListRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");

    QByteArray avatar = loadFile2ByteArray("D:\\A_Bit_Code\\micro-service\\ChatMockServer\\resource\\horse.png");
    for(int i = 0; i < 5; ++i)
    {
        pbPackage::FriendEvent event;
        event.setEventId("event" + QString::number(i));
        event.setSender(makeUserInfo(i,avatar));
        pbResp.event().push_back(event);
    }

    //3.构建http响应
    QByteArray body = pbResp.serialize(&serialize);
    QHttpServerResponse httpResp(body,QHttpServerResponse::StatusCode::Ok);
    httpResp.setHeader("Content-Type", "application/x-protobuf");
    return httpResp;
}

QHttpServerResponse HttpServer::getRecentMessage(const QHttpServerRequest &req)
{
    //1.解析请求
    pbPackage::GetRecentMsgReq pbReq;
    pbReq.deserialize(&this->serialize,req.body());
    LOG() << "[pbReq 获得最近消息列表] requestId = " << pbReq.requestId() << ", loginSessionId = " << pbReq.sessionId()
          << ", chatSessionId = " << pbReq.chatSessionId();

    //2.构造响应
    pbPackage::GetRecentMsgRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");

    QByteArray avatar = loadFile2ByteArray("D:\\A_Bit_Code\\micro-service\\ChatMockServer\\resource\\horse.png");

    //构造文本消息
    for(int i = 0; i < 30; ++i)
    {
        pbPackage::MessageInfo messageInfo = makeTextMessageInfo(i,"2000",avatar);
        pbResp.msgList().push_back(messageInfo);
    }
    //构造图片消息
    pbPackage::MessageInfo imageInfo = makeImageMessageInfo(30,"2000",avatar);
    pbResp.msgList().push_back(imageInfo);
    //构造文件消息
    pbPackage::MessageInfo fileInfo = makeFileMessageInfo(31,"2000",avatar);
    pbResp.msgList().push_back(fileInfo);
    //构造语音消息
    pbPackage::MessageInfo speechInfo = makeSpeechMessageInfo(32,"2000",avatar);
    pbResp.msgList().push_back(speechInfo);

    //3.构建http响应
    QByteArray body = pbResp.serialize(&serialize);
    QHttpServerResponse httpResp(body,QHttpServerResponse::StatusCode::Ok);
    httpResp.setHeader("Content-Type", "application/x-protobuf");
    LOG() << "响应成功";
    return httpResp;
}

QHttpServerResponse HttpServer::newMessage(const QHttpServerRequest &req)
{
    //1.解析请求
    pbPackage::NewMessageReq pbReq;
    pbReq.deserialize(&this->serialize,req.body());
    LOG() << "[Req发送消息] requestId = " << pbReq.requestId() << " loginSessionId = " << pbReq.sessionId()
          << "chatSessionId= " << pbReq.chatSessionId() <<", messageType=" << pbReq.message().messageType();

    if (pbReq.message().messageType() == pbPackage::MessageTypeGadget::MessageType::STRING) {
        LOG() << "发送的消息内容=" << pbReq.message().stringMessage().content();
    }

    //2.构造响应
    pbPackage::NewMessageRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");

    //3.构建http响应
    QByteArray body = pbResp.serialize(&serialize);
    QHttpServerResponse httpResp(body,QHttpServerResponse::StatusCode::Ok);
    httpResp.setHeader("Content-Type", "application/x-protobuf");
    return httpResp;
}

QHttpServerResponse HttpServer::setNickName(const QHttpServerRequest &req)
{
    //1.解析请求
    pbPackage::SetUserNicknameReq pbReq;
    pbReq.deserialize(&this->serialize,req.body());
    LOG() << "[Req设置昵称] requestId = " << pbReq.requestId() << " loginSessionId = " << pbReq.sessionId()
          << "nickName = " << pbReq.nickname();

    //2.构造响应
    pbPackage::SetUserNicknameRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");

    //3.构建http响应
    QByteArray body = pbResp.serialize(&serialize);
    QHttpServerResponse httpResp(body,QHttpServerResponse::StatusCode::Ok);
    httpResp.setHeader("Content-Type", "application/x-protobuf");
    return httpResp;
}

QHttpServerResponse HttpServer::setDesc(const QHttpServerRequest &req)
{
    //1.解析请求
    pbPackage::SetUserDescriptionReq pbReq;
    pbReq.deserialize(&this->serialize,req.body());
    LOG() << "[Req设置个性签名] requestId = " << pbReq.requestId() << " loginSessionId = " << pbReq.sessionId()
          << "nickName = " << pbReq.description();

    //2.构造响应
    pbPackage::SetUserDescriptionRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");

    //3.构建http响应
    QByteArray body = pbResp.serialize(&serialize);
    QHttpServerResponse httpResp(body,QHttpServerResponse::StatusCode::Ok);
    httpResp.setHeader("Content-Type", "application/x-protobuf");
    return httpResp;
}

QHttpServerResponse HttpServer::getPhoneVerifyCode(const QHttpServerRequest &req)
{
    //1.解析请求
    pbPackage::PhoneVerifyCodeReq pbReq;
    pbReq.deserialize(&this->serialize,req.body());
    LOG() << "[Req获取手机验证码] requestId = " << pbReq.requestId() << " phoneNumber = " << pbReq.phoneNumber();

    //2.构造响应
    pbPackage::PhoneVerifyCodeRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");
    pbResp.setVerifyCodeId("6666");

    //3.构建http响应
    QByteArray body = pbResp.serialize(&serialize);
    QHttpServerResponse httpResp(body,QHttpServerResponse::StatusCode::Ok);
    httpResp.setHeader("Content-Type", "application/x-protobuf");
    return httpResp;
}

QHttpServerResponse HttpServer::setPhone(const QHttpServerRequest &req)
{
    //1.解析请求
    pbPackage::SetUserPhoneNumberReq pbReq;
    pbReq.deserialize(&this->serialize,req.body());
    LOG() << "[设置手机号] requestId=" << pbReq.requestId()
          << " loginSessionId = " << pbReq.sessionId()
          << " phoneNumber= " << pbReq.phoneNumber()
          << " verifyCodeId= " << pbReq.phoneVerifyCodeId()
          << " verifyCode= " << pbReq.phoneVerifyCode();

    //2.构造响应
    pbPackage::SetUserPhoneNumberRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");

    //3.构建http响应
    QByteArray body = pbResp.serialize(&serialize);
    QHttpServerResponse httpResp(body,QHttpServerResponse::StatusCode::Ok);
    httpResp.setHeader("Content-Type", "application/x-protobuf");
    return httpResp;
}

QHttpServerResponse HttpServer::setAvatar(const QHttpServerRequest &req)
{
    //1.解析请求
    pbPackage::SetUserAvatarReq pbReq;
    pbReq.deserialize(&this->serialize,req.body());
    LOG() << "[Req修改头像] requestId=" << pbReq.requestId()
          << " loginSessionId = " << pbReq.sessionId();

    //2.构造响应
    pbPackage::SetUserAvatarRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");

    //3.构建http响应
    QByteArray body = pbResp.serialize(&serialize);
    QHttpServerResponse httpResp(body,QHttpServerResponse::StatusCode::Ok);
    httpResp.setHeader("Content-Type", "application/x-protobuf");
    return httpResp;
}

QHttpServerResponse HttpServer::removeFriend(const QHttpServerRequest &req)
{
    //1.解析请求
    pbPackage::FriendRemoveReq pbReq;
    pbReq.deserialize(&this->serialize,req.body());
    LOG() << "[Req删除好友] requestId=" << pbReq.requestId()
          << " loginSessionId = " << pbReq.sessionId()
          << "peerId = " << pbReq.peerId();

    //2.构造响应
    pbPackage::FriendRemoveRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");

    //3.构建http响应
    QByteArray body = pbResp.serialize(&serialize);
    QHttpServerResponse httpResp(body,QHttpServerResponse::StatusCode::Ok);
    httpResp.setHeader("Content-Type", "application/x-protobuf");
    return httpResp;
}

QHttpServerResponse HttpServer::applyFriend(const QHttpServerRequest &req)
{
    //1.解析请求
    pbPackage::FriendAddReq pbReq;
    pbReq.deserialize(&this->serialize,req.body());
    LOG() << "[pbReq添加好友] requestId=" << pbReq.requestId()
          << " loginSessionId = " << pbReq.sessionId()
          << "respondent = " << pbReq.respondentId();

    //2.构造响应
    pbPackage::FriendAddRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");
    pbResp.setNotifyEventId("");

    //3.构建http响应
    QByteArray body = pbResp.serialize(&serialize);
    QHttpServerResponse httpResp(body,QHttpServerResponse::StatusCode::Ok);
    httpResp.setHeader("Content-Type", "application/x-protobuf");
    return httpResp;
}

QHttpServerResponse HttpServer::addFriendProcess(const QHttpServerRequest &req)
{
    //1.解析请求
    pbPackage::FriendAddProcessReq pbReq;
    pbReq.deserialize(&this->serialize,req.body());
    LOG() << "[pbReq添加好友好友申请处理] requestId=" << pbReq.requestId()
          << " loginSessionId = " << pbReq.sessionId()
          << "applierID = " << pbReq.applyUserId();

    //2.构造响应
    pbPackage::FriendAddProcessRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");

    //3.构建http响应
    QByteArray body = pbResp.serialize(&serialize);
    QHttpServerResponse httpResp(body,QHttpServerResponse::StatusCode::Ok);
    httpResp.setHeader("Content-Type", "application/x-protobuf");
    return httpResp;
}

QHttpServerResponse HttpServer::createChatSession(const QHttpServerRequest &req)
{
    //1.解析请求
    pbPackage::ChatSessionCreateReq pbReq;
    pbReq.deserialize(&this->serialize,req.body());
    LOG() << "[pbReq创建会话] requestId=" << pbReq.requestId()
          << " loginSessionId = " << pbReq.sessionId()
          << "userIdList = " << pbReq.memberIdList();

    //2.构造响应
    pbPackage::ChatSessionCreateRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");

    //3.构建http响应
    QByteArray body = pbResp.serialize(&serialize);
    QHttpServerResponse httpResp(body,QHttpServerResponse::StatusCode::Ok);
    httpResp.setHeader("Content-Type", "application/x-protobuf");
    return httpResp;
}

QHttpServerResponse HttpServer::getMemberList(const QHttpServerRequest &req)
{
    //1.解析请求
    pbPackage::GetChatSessionMemberReq pbReq;
    pbReq.deserialize(&this->serialize,req.body());
    LOG() << "[pbReq创建会话] requestId=" << pbReq.requestId()
          << " loginSessionId = " << pbReq.sessionId()
          << " chatSessionId  = " << pbReq.chatSessionId();

    //2.构造响应
    pbPackage::GetChatSessionMemberRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");

    QByteArray avatar = loadFile2ByteArray("D:\\A_Bit_Code\\micro-service\\ChatMockServer\\resource\\horse.png");
    for(int i = 0; i < 10; ++i)
    {
        pbPackage::UserInfo userInfo = makeUserInfo(i,avatar);
        pbResp.memberInfoList().push_back(userInfo);
    }

    //3.构建http响应
    QByteArray body = pbResp.serialize(&serialize);
    QHttpServerResponse httpResp(body,QHttpServerResponse::StatusCode::Ok);
    httpResp.setHeader("Content-Type", "application/x-protobuf");
    return httpResp;
}

QHttpServerResponse HttpServer::searchFriend(const QHttpServerRequest &req)
{
    //1.解析请求
    pbPackage::FriendSearchReq pbReq;
    pbReq.deserialize(&this->serialize,req.body());
    LOG() << "[pbReq搜索好友] requestId=" << pbReq.requestId()
          << " loginSessionId = " << pbReq.sessionId()
          << " searchKey  = " << pbReq.searchKey();

    //2.构造响应
    pbPackage::FriendSearchRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");

    QByteArray avatar = loadFile2ByteArray("D:\\A_Bit_Code\\micro-service\\ChatMockServer\\resource\\horse.png");
    for(int i = 0; i < 10; ++i)
    {
        pbPackage::UserInfo userInfo = makeUserInfo(i,avatar);
        pbResp.userInfo().push_back(userInfo);
    }

    //3.构建http响应
    QByteArray body = pbResp.serialize(&serialize);
    QHttpServerResponse httpResp(body,QHttpServerResponse::StatusCode::Ok);
    httpResp.setHeader("Content-Type", "application/x-protobuf");
    return httpResp;
}

QHttpServerResponse HttpServer::searchHistoryByKey(const QHttpServerRequest &req)
{
    //1.解析请求
    pbPackage::MsgSearchReq pbReq;
    pbReq.deserialize(&this->serialize,req.body());
    LOG() << "[pbReq通过关键字搜索历史消息] requestId=" << pbReq.requestId()
          << " loginSessionId = " << pbReq.sessionId()
          << " chatSessionId = " << pbReq.chatSessionId()
          << " searchKey  = " << pbReq.searchKey();

    //2.构造响应
    pbPackage::MsgSearchRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");

    QByteArray avatar = loadFile2ByteArray("D:\\A_Bit_Code\\micro-service\\ChatMockServer\\resource\\horse.png");
    for(int i = 0; i < 20; ++i)
    {
        pbPackage::MessageInfo message = makeTextMessageInfo(i,pbReq.chatSessionId(),avatar);
        pbResp.msgList().push_back(message);
    }
    //测试图片消息
    pbPackage::MessageInfo imageMessage = makeImageMessageInfo(10,pbReq.chatSessionId(),avatar);
    pbResp.msgList().push_back(imageMessage);

    //测试文件消息
    pbPackage::MessageInfo fileMessage = makeFileMessageInfo(11,pbReq.chatSessionId(),avatar);
    pbResp.msgList().push_back(fileMessage);

    //测试语音消息
    pbPackage::MessageInfo speechMessage = makeSpeechMessageInfo(12,pbReq.chatSessionId(),avatar);
    pbResp.msgList().push_back(speechMessage);


    //3.构建http响应
    QByteArray body = pbResp.serialize(&serialize);
    QHttpServerResponse httpResp(body,QHttpServerResponse::StatusCode::Ok);
    httpResp.setHeader("Content-Type", "application/x-protobuf");
    return httpResp;
}

QHttpServerResponse HttpServer::searchHistoryByTime(const QHttpServerRequest &req)
{
    //1.解析请求
    pbPackage::GetHistoryMsgReq pbReq;
    pbReq.deserialize(&this->serialize,req.body());
    LOG() << "[pbReq通过时间搜索历史消息] requestId=" << pbReq.requestId()
          << " loginSessionId = " << pbReq.sessionId()
          << " currentChatSessionId = " << pbReq.chatSessionId()
          << " startTime = " << pbReq.startTime()
          << " startTime = " << pbReq.startTime();

    //2.构造响应
    pbPackage::GetHistoryMsgRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");

    QByteArray avatar = loadFile2ByteArray("D:\\A_Bit_Code\\micro-service\\ChatMockServer\\resource\\horse.png");
    for(int i = 0; i < 20; ++i)
    {
        pbPackage::MessageInfo message = makeTextMessageInfo(i,pbReq.chatSessionId(),avatar);
        pbResp.msgList().push_back(message);
    }
    //3.构建http响应
    QByteArray body = pbResp.serialize(&serialize);
    QHttpServerResponse httpResp(body,QHttpServerResponse::StatusCode::Ok);
    httpResp.setHeader("Content-Type", "application/x-protobuf");
    return httpResp;
}

QHttpServerResponse HttpServer::userLogin(const QHttpServerRequest &req)
{
    //1.解析请求
    pbPackage::UserLoginReq pbReq;
    pbReq.deserialize(&serialize,req.body());
    LOG() << "[pbReq用户登录] requestId=" << pbReq.requestId()
          << " nickname = " << pbReq.nickname()
          << " password = " << pbReq.password();

    pbPackage::UserLoginRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");
    pbResp.setLoginSessionId("testLogin");
    QByteArray body = pbResp.serialize(&serialize);
    QHttpServerResponse httpResp(body,QHttpServerResponse::StatusCode::Ok);
    httpResp.setHeader("Content-Type", "application/x-protobuf");
    return httpResp;
}

QHttpServerResponse HttpServer::userRegister(const QHttpServerRequest &req)
{
    //1.解析请求
    pbPackage::UserRegisterReq pbReq;
    pbReq.deserialize(&serialize,req.body());
    LOG() << "[pbReq用户注册] requestId=" << pbReq.requestId()
          << " nickname = " << pbReq.nickname()
          << " password = " << pbReq.password();
    pbPackage::UserRegisterRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");
    QByteArray body = pbResp.serialize(&serialize);
    QHttpServerResponse httpResp(body,QHttpServerResponse::StatusCode::Ok);
    httpResp.setHeader("Content-Type", "application/x-protobuf");
    return httpResp;
}

QHttpServerResponse HttpServer::phoneLogin(const QHttpServerRequest &req)
{
    pbPackage::PhoneLoginReq pbReq;
    pbReq.deserialize(&serialize,req.body());
    LOG() << "[pbReq手机号登录]请求"
          << " requestId = " << pbReq.requestId()
          << " verifyCode = " << pbReq.verifyCode()
          << " verifyCodeId = " << pbReq.verifyCodeId()
          << " phoneNumber = " << pbReq.phoneNumber();
    pbPackage::PhoneLoginRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");
    pbResp.setLoginSessionId("9990000");
    QByteArray body = pbResp.serialize(&serialize);
    QHttpServerResponse httpResp(body,QHttpServerResponse::StatusCode::Ok);
    httpResp.setHeader("Content-Type", "application/x-protobuf");
    return httpResp;
}

QHttpServerResponse HttpServer::phoneRegister(const QHttpServerRequest &req)
{
    //1.解析请求
    pbPackage::PhoneRegisterReq pbReq;
    pbReq.deserialize(&serialize,req.body());
    LOG() << "[pbReq手机号注册]请求"
          << " requestId = " << pbReq.requestId()
          << " verifyCode = " << pbReq.verifyCode()
          << " verifyCodeId = " << pbReq.verifyCodeId()
          << " phoneNumber = " << pbReq.phoneNumber();
    pbPackage::PhoneRegisterRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");

    QByteArray body = pbResp.serialize(&serialize);
    QHttpServerResponse httpResp(body,QHttpServerResponse::StatusCode::Ok);
    httpResp.setHeader("Content-Type", "application/x-protobuf");
    return httpResp;
}

QHttpServerResponse HttpServer::getSingleFile(const QHttpServerRequest &req)
{
    //1.解析请求
    pbPackage::GetSingleFileReq pbReq;
    pbReq.deserialize(&serialize,req.body());
    LOG() << "[pbReq获取单个文件]请求"
          << " requestId = " << pbReq.requestId()
          << " fileId = " << pbReq.fileId();

    pbPackage::GetSingleFileRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");

    //构造响应的文件
    pbPackage::FileDownloadData fileDownloadData;
    fileDownloadData.setFileId(pbReq.fileId());
    //根据不同的fileId,构建不同的响应
    if(pbReq.fileId() == "testImage")
    {
        fileDownloadData.setFileContent(loadFile2ByteArray("D:\\A_Bit_Code\\micro-service\\ChatMockServer\\resource\\lion.png"));
    }
    else if(pbReq.fileId() == "testFile")
    {
        fileDownloadData.setFileContent(loadFile2ByteArray("D:\\A_Book\\test.txt"));
    }
    else if(pbReq.fileId() == "testSpeech")
    {
        fileDownloadData.setFileContent(loadFile2ByteArray("C:\\Users\\王康\\AppData\\Roaming\\ChatClient\\sound\\tmpPlay.pcm"));
    }
    else
    {
        pbResp.setSuccess(false);
        pbResp.setErrmsg("fileId不是预期的测试fileId");
    }
    pbResp.setFileData(fileDownloadData);

    QByteArray body = pbResp.serialize(&serialize);
    QHttpServerResponse httpResp(body,QHttpServerResponse::StatusCode::Ok);
    httpResp.setHeader("Content-Type", "application/x-protobuf");
    return httpResp;
}

QHttpServerResponse HttpServer::speechRecognition(const QHttpServerRequest &req)
{
    //1.解析请求
    pbPackage::SpeechRecognitionReq pbReq;
    pbReq.deserialize(&serialize,req.body());
    LOG() << "[pbReq语音识别]请求"
          << " requestId = " << pbReq.requestId()
          << " sessionId = " << pbReq.sessionId();

    pbPackage::SpeechRecognitionRsp pbResp;
    pbResp.setRequestId(pbReq.requestId());
    pbResp.setSuccess(true);
    pbResp.setErrmsg("");
    pbResp.setRecognitionResult("这是一段语音，这是一段语音");

    QByteArray body = pbResp.serialize(&serialize);
    QHttpServerResponse httpResp(body,QHttpServerResponse::StatusCode::Ok);
    httpResp.setHeader("Content-Type", "application/x-protobuf");
    return httpResp;
}

WebSocketServer* WebSocketServer::instance = nullptr;

WebSocketServer::WebSocketServer()
    :webSocketServer("websocket server",QWebSocketServer::NonSecureMode)
{

}

WebSocketServer *WebSocketServer::getInstance()
{
    if(instance == nullptr)
    {
        instance = new WebSocketServer();
    }
    return instance;
}

//针对WebSocketServer进行初始化工作
bool WebSocketServer::init()
{
    //1.连接信号槽
    connect(&webSocketServer,&QWebSocketServer::newConnection,this,[=](){
        qDebug() << "[websocket] 连接建立成功";

        //获取用来通信的socket对象
        QWebSocket* socket = webSocketServer.nextPendingConnection();

        connect(socket,&QWebSocket::disconnected,this,[=](){
            qDebug() << "[websocket] 连接断开";

            //断开发送信息的信号槽
            disconnect(this,&WebSocketServer::sendTextResp,this,nullptr);
            disconnect(this,&WebSocketServer::sendImageMessage,this,nullptr);
            disconnect(this,&WebSocketServer::sendFileMessage,this,nullptr);
            disconnect(this,&WebSocketServer::sendSpeechMessage,this,nullptr);

            disconnect(this,&WebSocketServer::deleteFriendResp,this,nullptr);
            disconnect(this,&WebSocketServer::sendFriendApply,this,nullptr);
            disconnect(this,&WebSocketServer::sendAddFriendApply,this,nullptr);
            disconnect(this,&WebSocketServer::sendCreateChatSession,this,nullptr);

        });

        connect(socket,&QWebSocket::errorOccurred,this,[=](QAbstractSocket::SocketError error){
            qDebug() << "[websocket] 连接出错" << error;
        });

        connect(socket,&QWebSocket::textMessageReceived,this,[=](const QString& message){
            qDebug() << "[websocket] 收到文本消息" << message;
        });


        connect(socket,&QWebSocket::binaryMessageReceived,this,[=](const QByteArray& byteArray){
            qDebug() << "[websocket] 收到二进制消息" << byteArray.size();
        });

        //发送文本消息的通知
        connect(this,&WebSocketServer::sendTextResp,this,[=](){
            //此处可以捕获到socket
            if(socket == nullptr || !socket->isValid())
            {
                LOG() << "socket对象无效";
                return;
            }
            QByteArray avatar = loadFile2ByteArray("D:\\A_Bit_Code\\micro-service\\ChatMockServer\\resource\\lion.png");
            pbPackage::MessageInfo messageInfo = makeTextMessageInfo(this->messageIndex++,"2000",avatar);

            pbPackage::NotifyNewMessage notifyNewMessage;
            notifyNewMessage.setMessageInfo(messageInfo);

            pbPackage::NotifyMessage notifyMessage;
            notifyMessage.setNotifyEventId("");
            notifyMessage.setNotifyType(pbPackage::NotifyTypeGadget::NotifyType::CHAT_MESSAGE_NOTIFY);
            notifyMessage.setNewMessageInfo(notifyNewMessage);

            QByteArray body = notifyMessage.serialize(&serialize);

            socket->sendBinaryMessage(body);
            LOG() << "发送文本消息" << messageInfo.message().stringMessage().content();
        });

        //发送图片消息的通知
        connect(this,&WebSocketServer::sendImageMessage,this,[=](){
            //此处可以捕获到socket
            if(socket == nullptr || !socket->isValid())
            {
                LOG() << "socket对象无效";
                return;
            }
            QByteArray avatar = loadFile2ByteArray("D:\\A_Bit_Code\\micro-service\\ChatMockServer\\resource\\lion.png");
            pbPackage::MessageInfo messageInfo = makeImageMessageInfo(this->messageIndex++,"2000",avatar);

            pbPackage::NotifyNewMessage notifyNewMessage;
            notifyNewMessage.setMessageInfo(messageInfo);

            pbPackage::NotifyMessage notifyMessage;
            notifyMessage.setNotifyEventId("");
            notifyMessage.setNotifyType(pbPackage::NotifyTypeGadget::NotifyType::CHAT_MESSAGE_NOTIFY);
            notifyMessage.setNewMessageInfo(notifyNewMessage);

            QByteArray body = notifyMessage.serialize(&serialize);
            socket->sendBinaryMessage(body);
            LOG() << "发送图片消息" ;
        });

        //发送文件消息的通知
        connect(this,&WebSocketServer::sendFileMessage,this,[=](){
            //此处可以捕获到socket
            if(socket == nullptr || !socket->isValid())
            {
                LOG() << "socket对象无效";
                return;
            }
            QByteArray avatar = loadFile2ByteArray("D:\\A_Bit_Code\\micro-service\\ChatMockServer\\resource\\lion.png");
            pbPackage::MessageInfo messageInfo = makeFileMessageInfo(this->messageIndex++,"2000",avatar);

            pbPackage::NotifyNewMessage notifyNewMessage;
            notifyNewMessage.setMessageInfo(messageInfo);

            pbPackage::NotifyMessage notifyMessage;
            notifyMessage.setNotifyEventId("");
            notifyMessage.setNotifyType(pbPackage::NotifyTypeGadget::NotifyType::CHAT_MESSAGE_NOTIFY);
            notifyMessage.setNewMessageInfo(notifyNewMessage);

            QByteArray body = notifyMessage.serialize(&serialize);
            socket->sendBinaryMessage(body);
            LOG() << "发送文件消息" ;
        });

        //发送语音消息的通知
        connect(this,&WebSocketServer::sendSpeechMessage,this,[=](){
            //此处可以捕获到socket
            if(socket == nullptr || !socket->isValid())
            {
                LOG() << "socket对象无效";
                return;
            }
            QByteArray avatar = loadFile2ByteArray("D:\\A_Bit_Code\\micro-service\\ChatMockServer\\resource\\lion.png");
            pbPackage::MessageInfo messageInfo = makeSpeechMessageInfo(this->messageIndex++,"2000",avatar);

            pbPackage::NotifyNewMessage notifyNewMessage;
            notifyNewMessage.setMessageInfo(messageInfo);

            pbPackage::NotifyMessage notifyMessage;
            notifyMessage.setNotifyEventId("");
            notifyMessage.setNotifyType(pbPackage::NotifyTypeGadget::NotifyType::CHAT_MESSAGE_NOTIFY);
            notifyMessage.setNewMessageInfo(notifyNewMessage);

            QByteArray body = notifyMessage.serialize(&serialize);
            socket->sendBinaryMessage(body);
            LOG() << "发送语音消息" ;
        });

        //发送删除好友的通知
        connect(this,&WebSocketServer::deleteFriendResp,this,[=](){
            //此处可以捕获到socket
            if(socket == nullptr || !socket->isValid())
            {
                LOG() << "socket对象无效";
                return;
            }
            pbPackage::NotifyFriendRemove notifyFriendRemove;
            notifyFriendRemove.setUserId("1002");

            pbPackage::NotifyMessage notifyMessage;
            notifyMessage.setNotifyEventId("");
            notifyMessage.setNotifyType(pbPackage::NotifyTypeGadget::NotifyType::FRIEND_REMOVE_NOTIFY);
            notifyMessage.setFriendRemove(notifyFriendRemove);

            QByteArray body = notifyMessage.serialize(&serialize);
            socket->sendBinaryMessage(body);
            LOG() << "通知对方删除好友完毕 userId = 1000";
        });

        //发送好友申请的通知
        connect(this,&WebSocketServer::sendFriendApply,this,[=](){
            if(socket == nullptr || !socket->isValid())
            {
                LOG() << "socket对象无效";
                return;
            }
            QByteArray avatar = loadFile2ByteArray("D:\\A_Bit_Code\\micro-service\\ChatMockServer\\resource\\lion.png");
            pbPackage::UserInfo userInfo = makeUserInfo(666,avatar);

            pbPackage::NotifyFriendAddApply nofifyFriendApply;
            nofifyFriendApply.setUserInfo(userInfo);

            pbPackage::NotifyMessage notifyMessage;
            notifyMessage.setNotifyEventId("");
            notifyMessage.setNotifyType(pbPackage::NotifyTypeGadget::NotifyType::FRIEND_ADD_APPLY_NOTIFY);
            notifyMessage.setFriendAddApply(nofifyFriendApply);

            QByteArray body = notifyMessage.serialize(&serialize);
            socket->sendBinaryMessage(body);
            LOG() << "通知好友申请完毕";
        });


        //同意/拒绝使用同一个接口
        connect(this,&WebSocketServer::sendAddFriendApply,this,[=](bool agree){
            if(socket == nullptr || !socket->isValid())
            {
                LOG() << "socket对象无效";
                return;
            }
            QByteArray avatar = loadFile2ByteArray("D:\\A_Bit_Code\\micro-service\\ChatMockServer\\resource\\lion.png");
            pbPackage::UserInfo userInfo = makeUserInfo(100,avatar);

            pbPackage::NotifyFriendAddProcess nofifyFriendApplyProcess;
            nofifyFriendApplyProcess.setUserInfo(userInfo);
            nofifyFriendApplyProcess.setAgree(agree);

            pbPackage::NotifyMessage notifyMessage;
            notifyMessage.setNotifyEventId("");
            notifyMessage.setNotifyType(pbPackage::NotifyTypeGadget::NotifyType::FRIEND_ADD_PROCESS_NOTIFY);
            notifyMessage.setFriendProcessResult(nofifyFriendApplyProcess);

            QByteArray body = notifyMessage.serialize(&serialize);
            socket->sendBinaryMessage(body);
            LOG() << "通知对方好友申请通过 userID = " << userInfo.userId() << " argee = " << agree;
        });

        //发送创建群聊的通知
        connect(this,&WebSocketServer::sendCreateChatSession,this,[=](){
            if(socket == nullptr || !socket->isValid())
            {
                LOG() << "socket对象无效";
                return;
            }
            QByteArray avatar = loadFile2ByteArray("D:\\A_Bit_Code\\micro-service\\ChatMockServer\\resource\\lion.png");
            pbPackage::MessageInfo messageInfo = makeTextMessageInfo(0,"2100",avatar);

            pbPackage::ChatSessionInfo chatSessionInfo;
            chatSessionInfo.setChatSessionId("2100");
            chatSessionInfo.setChatSessionName("新的群聊");
            chatSessionInfo.setSingleChatFriendId("");
            chatSessionInfo.setAvatar(avatar);
            chatSessionInfo.setPrevMessage(messageInfo);

            pbPackage::NotifyNewChatSession notifyNewChatSesion;
            notifyNewChatSesion.setChatSessionInfo(chatSessionInfo);

            pbPackage::NotifyMessage notifyMessage;
            notifyMessage.setNotifyEventId("");
            notifyMessage.setNotifyType(pbPackage::NotifyTypeGadget::NotifyType::CHAT_SESSION_CREATE_NOTIFY);
            notifyMessage.setNewChatSessionInfo(notifyNewChatSesion);

            QByteArray body = notifyMessage.serialize(&serialize);
            socket->sendBinaryMessage(body);
            LOG() << "新的群聊已经创建 chatSessionID = " << chatSessionInfo.chatSessionId();
        });

    });
    //2.绑定端口，启动服务
    bool ok = webSocketServer.listen(QHostAddress::Any,8001);
    return ok;
}
